<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span class="title">{{ title }}</span>
          <el-button type="primary" @click="handleBack">返回列表</el-button>
        </div>
      </template>

      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">

        <!-- 修改社区下拉框，添加监听事件 -->
        <el-form-item label="社区" prop="communityId">
          <el-select
              v-model="form.communityId"
              placeholder="请选择社区"
              clearable
              filterable
          >
            <el-option
                v-for="ops in optiones"
                :key="ops.communityId"
                :label="ops.name"
                :value="ops.communityId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="通知标题" prop="title">
          <el-input
              v-model="form.title"
              placeholder="请输入通知标题"
              :disabled="mode === 'view'"
          />
        </el-form-item>

        <el-form-item label="通知类型" prop="noticeType">
          <el-select
              v-model="form.noticeType"
              placeholder="请选择通知类型"
              :disabled="mode === 'view'"
              style="width: 100%"
          >
            <el-option label="社区公告" value="community"/>
            <el-option label="紧急通知" value="urgent"/>
            <el-option label="活动通知" value="activity"/>
            <el-option label="维修通知" value="repair"/>
          </el-select>
        </el-form-item>

        <el-form-item label="通知内容" prop="content">
          <el-input
              v-model="form.content"
              type="textarea"
              placeholder="请输入通知内容"
              :rows="6"
              :disabled="mode === 'view'"
              show-word-limit
              maxlength="1000"
          />
        </el-form-item>

        <!-- 修改附件组件为PDF上传组件 -->
        <el-form-item label="附件" prop="attachments">
          <el-upload
              ref="uploadRef"
              class="upload-demo"
              action="#"
              :limit="3"
              :file-list="fileList"
              :before-upload="beforeUpload"
              :on-remove="handleRemove"
              :on-change="handleChange"
              :auto-upload="false"
              accept=".pdf"
              :disabled="mode === 'view'"
          >
            <template #trigger>
              <el-button type="primary" :disabled="mode === 'view'">选择PDF文件</el-button>
            </template>
            <template #tip>
              <div class="el-upload__tip">
                只能上传PDF文件，且不超过10MB
              </div>
            </template>
          </el-upload>
        </el-form-item>

        <el-form-item label="发布人" prop="publisher">
          <el-input
              v-model="form.publisher"
              placeholder="请输入发布人"
              :disabled="mode === 'view'"
          />
        </el-form-item>

        <el-form-item label="发布时间" prop="publishTime">
          <el-date-picker
              v-model="form.publishTime"
              type="datetime"
              placeholder="请选择发布时间"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%"
              :disabled="mode === 'view'"
          />
        </el-form-item>

        <el-form-item label="接受范围" prop="recipientScope">
          <el-input
              v-model="form.title"
              placeholder="请输入通知接收的范围"
              :disabled="mode === 'view'"
          />
        </el-form-item>

        <el-form-item v-if="mode !== 'view'">
          <el-button type="primary" @click="submitForm">保 存</el-button>
          <el-button @click="handleBack">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted} from 'vue'
import {useRouter} from 'vue-router'
import {ElMessage} from 'element-plus'
import {addNotice} from '@/api/property/notice'
import {getoption} from "@/api/property/repair"

const router = useRouter()
const formRef = ref()
const uploadRef = ref()
const mode = ref('add')
const title = ref('新增物业公告')
const optiones = ref([])
const fileList = ref([])

const form = reactive({
  communityId: '',
  title: '',
  noticeType: '',
  content: '',
  attachments: '',
  publisher: '',
  publishTime: '',
  recipientScope: '全体楼宇'
})

// 获取社区选项
const fetchOptions = async () => {
  try {
    const response = await getoption()
    optiones.value = response.data || response
  } catch (error) {
    console.log("获取数据失败:", error)
  }
}

// 文件上传前的验证
const beforeUpload = (file) => {
  const isPDF = file.type === 'application/pdf'
  const isLt10M = file.size / 1024 / 1024 < 10

  if (!isPDF) {
    ElMessage.error('只能上传PDF格式的文件!')
    return false
  }
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过10MB!')
    return false
  }
  return true
}

// 处理文件移除
const handleRemove = (file, fileList) => {
  // 更新文件列表
  updateAttachments(fileList)
}

// 处理文件变化
const handleChange = (file, fileList) => {
  // 验证文件格式和大小
  if (file.raw) {
    const isValid = beforeUpload(file.raw)
    if (!isValid) {
      // 移除无效文件
      const index = fileList.indexOf(file)
      if (index > -1) {
        fileList.splice(index, 1)
      }
      return
    }
  }

  // 更新文件列表
  updateAttachments(fileList)
}

// 更新附件数据
const updateAttachments = (files) => {
  // 将文件列表转换为JSON字符串格式，存储文件信息
  const attachments = files.map(file => ({
    name: file.name,
    url: file.url || '', // 如果有上传后的URL
    size: file.size,
    uid: file.uid
  }))

  form.attachments = JSON.stringify(attachments)
}

const submitForm = async () => {
  try {
    // 验证表单
    if (!formRef.value) return
    await formRef.value.validate()

    // 处理文件上传
    if (fileList.value.length > 0) {
      // 这里可以添加实际的文件上传逻辑
      // 例如调用上传API，获取文件URL后更新form.attachments
      // await uploadFiles()
    }

    await addNotice(form)
    ElMessage.success('新增成功')
    handleBack()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('新增失败')
  }
}

const handleBack = () => {
  router.back()
}

// 页面加载时获取社区选项
onMounted(() => {
  fetchOptions();

  // 如果有编辑数据，初始化文件列表
  if (form.attachments) {
    try {
      const attachments = JSON.parse(form.attachments)
      fileList.value = attachments.map(att => ({
        name: att.name,
        url: att.url,
        size: att.size,
        uid: att.uid
      }))
    } catch (e) {
      console.error('解析附件数据失败:', e)
    }
  }
})
</script>

<style scoped lang="scss">
.app-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

:deep(.el-card__body) {
  padding: 20px;
}

:deep(.el-form-item) {
  margin-bottom: 22px;
}

.upload-demo {
  width: 100%;
}
</style>